package com.iretailer.report.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.PhysicalCameraZone;
import com.iretailer.report.dto.QueryOption;
import com.iretailer.report.mapper.PhysicalZonesMapper;
import com.iretailer.report.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: xjw
 * @Date: 2019/1/23 16:29
 * @Description:
 */
@Service
public class PhysicalzonesService extends ServiceImpl<PhysicalZonesMapper, PhysicalZones> {
    @Autowired
    private PhysicalZonesMapper physicalZonesMapper;
    @Autowired
    private CameraZoneService cameraZoneService;
    @Autowired
    private CategoriesService categoriesService;
    @Autowired
    private PhysicalZoneCameraZoneService physicalZoneCameraZoneService;
    @Autowired
    private PhysicalZoneDeviceService physicalZoneDeviceService;
    @Autowired
    private UserMallService userMallService;

    public PageResult<PhysicalZoneMall> grid(String userId, Integer enabled, String mallName, String name, String zoneTypeName, QueryOption queryOption) {
        Page page = new Page<PhysicalZoneMall>(1, Long.MAX_VALUE);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("1", 1);
        if (enabled != null) {
            queryWrapper.eq("enabled", enabled);
        }
        if (mallName != null) {
            queryWrapper.like("mallName", mallName);
        }
        if (name != null) {
            queryWrapper.like("name", name);
        }
        if (zoneTypeName != null) {
            queryWrapper.like("zoneTypeName", zoneTypeName);
        }
        queryOption.judge(page, queryWrapper);
        if (userId != null) {
//            List<String> childens = userService.getTreeId(userId);
//            childens.add(userId);
//            List<String> mallIds = userMallService.selectMallIdsByUserIds(childens);
//            if (mallIds.size() == 0) {
//                mallIds.add("1");
//            }
            List<String> mallIds = userMallService.selectUserMallIds(userId);
            queryWrapper.in("mallId", mallIds);
        }
        physicalZonesMapper.selectPagePhysicalZoneMall(page, queryWrapper);
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    /**
     * @Author xjw
     * @Date 2019/1/23 16:42
     * @Description :  根据 CameraZoneId 进行关联
     **/
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean connectByCamera(Long cameraZoneId, List<PhysicalZoneMall> physicalZoneMalls) {
        List<PhysicalZoneCameraZone> param = new ArrayList<>();
        for (PhysicalZoneMall pzm : physicalZoneMalls) {
            int reverse = pzm.getReverse() >= 0 ? 1 : -1;
            param.add(new PhysicalZoneCameraZone(cameraZoneId, pzm.getId(), reverse));
        }
        //删除所有关联
        physicalZoneCameraZoneService.remove(new QueryWrapper<PhysicalZoneCameraZone>().lambda().eq(PhysicalZoneCameraZone::getCameraZoneId, cameraZoneId));
        if (param.size() > 0) {
            physicalZoneCameraZoneService.saveBatch(param);
        }
        return true;
    }

    /**
     * @Author xjw
     * @Date 2019/1/23 16:42
     * @Description :  根据 physicalZoneId 进行关联
     **/
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean connectByPhysical(long physicalZoneId, List<CameraZoneCamera> cameraZoneCameras) {
        List<PhysicalZoneCameraZone> param = new ArrayList<>();
        for (CameraZoneCamera camera : cameraZoneCameras) {
            int reverse = camera.getReverse() >= 0 ? 1 : -1;
            param.add(new PhysicalZoneCameraZone(camera.getId(), physicalZoneId, reverse));
        }
        //删除所有关联
        physicalZoneCameraZoneService.remove(new QueryWrapper<PhysicalZoneCameraZone>().lambda().eq(PhysicalZoneCameraZone::getPhysicalzoneId, physicalZoneId));
        if (param.size() > 0) {
            physicalZoneCameraZoneService.saveBatch(param);
        }
        return true;
    }

    public List<PhysicalZoneMall> setCmaeraZones(List<PhysicalZoneMall> physicalZones) {
        if (physicalZones != null && physicalZones.size() > 0) {
            Set<Long> phyzoneIds = physicalZones.stream().map(pz -> {
                return pz.getId();
            }).collect(Collectors.toSet());

            List<CameraZoneCamera> cameraZones = cameraZoneService.selectByEnabled_PhysicalZoneIds(1, new ArrayList<>(phyzoneIds));
            Map<Long, List<CameraZoneCamera>> cameraZonesMap = cameraZones.stream().collect(Collectors.groupingBy(CameraZoneCamera::getPhysicalZoneId));
            physicalZones.forEach(it -> {
                List<CameraZoneCamera> czs = cameraZonesMap.get(it.getId());
                if (czs != null) {
                    it.setCameraZones(czs);
                    it.setCameraZoneIds(czs.stream().map(cz -> {
                        return cz.getId();
                    }).collect(Collectors.toList()));
                } else {
                    it.setCameraZones(new ArrayList<>());
                }
            });
            return physicalZones;
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 查出所有的和CameraZone关联关系
     */
    public List<PhysicalCameraZone> getAllPZCameraZone() {
        return physicalZonesMapper.getAllPZCameraZone();
    }

    /**
     * 根据 phyiscalZoneId 删除所有的关联
     */
    public int deletePZCameraZoneByPhysicalZoneId(int physicalZoneId) {
        return physicalZonesMapper.deletePZCameraZoneByPhysicalZoneId(physicalZoneId);
    }

    /**
     * 批量的插入 physicalZone 和 CameraZone关联关系
     * Map 中的 可以为 CamerazoneId,PhysicalzonesId,reverse
     */
    public int batchInsertPhysicalZonesCameraZone(List<PhysicalCameraZone> param) {
        return physicalZonesMapper.batchInsertPhysicalZonesCameraZone(param);
    }


    /**
     * zoneTypeId 为null 或者 '' 则查询全部
     * 返回中包含 mallName
     */
    public List<PhysicalZoneMall> selectByZoneTypeId(String zoneTypeId) {
        return physicalZonesMapper.selectByZoneTypeId(zoneTypeId);
    }

    /**
     * 根据 MallId 查询
     */
    public List<PhysicalZoneMall> selectByEnabled_MallId(Integer enabled, String mallId) {
        return physicalZonesMapper.selectByEnabled_MallId(enabled, mallId);
    }


    public List<PhysicalZoneMall> selectByIds(List<String> ids) {
        if (ids.size() > 0) {
            return physicalZonesMapper.selectByIds(ids);
        } else {
            return null;
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean saveOrUpdate(PhysicalZones physicalZones, String userName) {
        physicalZones.setUpdateUser(userName);
        physicalZones.setUpdateTime(LocalDateTime.now());
        if (physicalZones.getZoneTypeId() != null) {
            Categories categories = categoriesService.getById(physicalZones.getZoneTypeId());
            physicalZones.setZoneTypeName(categories.getName());
        }
        if (physicalZones.getId() != null && physicalZones.getId() > 0) {
            physicalZonesMapper.updateById(physicalZones);
            return true;
        } else {
            physicalZonesMapper.insert(physicalZones);
            return true;
        }
    }

    public boolean delete(Long id) {
        physicalZonesMapper.deleteById(id);
        return true;
    }

    /**
     * 用于 删除 cameraZone 的时候 检出 有没有被关联的
     */
    public List<PhysicalZoneMall> selectPhysicalZonesByEnabled_CameraZoneId(Integer enabled, Long cameraZoneId) {
        return physicalZonesMapper.selectPhysicalZonesByEnabled_CameraZoneId(enabled, cameraZoneId);
    }

    /**
     * 用于删除 device 的时候，检查 有没有被关联的
     */
    public List<PhysicalZones> selectBy_deviceId(String deviceId) {
        return physicalZonesMapper.selectBy_deviceId(deviceId);
    }

    /**
     * 根据 mallId 的List 的集合
     * zoneTypeId
     */
    public List<PhysicalZoneMall> selectByMallIds_ZoneTypeId(List<String> mallIds, String zoneTypeId) {

        if (mallIds.size() > 0) {
            return physicalZonesMapper.selectByMallIds_ZoneTypeId(mallIds, zoneTypeId);
        } else {
            return new ArrayList<>();
        }
    }

    public List<PhysicalZoneMall> selectByMallIds_ZoneTypeIds(List<String> mallIds, List<String> zoneTypeIds) {

        if (mallIds.size() > 0) {
            return physicalZonesMapper.selectByMallIds_ZoneTypeIds(mallIds, zoneTypeIds);
        } else {
            return new ArrayList<>();
        }
    }

    public List<PhysicalZoneMall> selectPhysicalZoneZoneType(Integer enabled, List<String> mallIds) {
        return physicalZonesMapper.selectPhysicalZoneZoneType(enabled, mallIds);
    }

    public List<PhysicalZoneMall> selectPZZTByMallIdZoneTypeEnable(Integer enabled, List<String> mallIds, List<String> zoneTypes) {
        return physicalZonesMapper.selectPZZTByMallIdZoneTypeEnable(enabled, mallIds, zoneTypes);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean deletePhysicalByIds(List<Long> ids) {
        physicalZoneCameraZoneService.remove(new QueryWrapper<PhysicalZoneCameraZone>().lambda().in(PhysicalZoneCameraZone::getPhysicalzoneId, ids));
        physicalZoneDeviceService.remove(new QueryWrapper<PhysicalZoneDevice>().lambda().in(PhysicalZoneDevice::getPhysicalzoneId, ids));
        removeByIds(ids);
        return true;
    }
}
